package com.sita.cfmoto.ui.activity;

import android.bluetooth.BluetoothClass;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.sita.cfmoto.R;
import com.sita.cfmoto.model.DeviceFaultModel;
import com.sita.cfmoto.model.FaultMapping;
import com.sita.cfmoto.rest.RestClient;
import com.sita.cfmoto.rest.model.BindedVehicle;
import com.sita.cfmoto.rest.model.RestResponse;
import com.sita.cfmoto.rest.model.request.CfmotorCommonRequest2;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.ui.adapter.DeviceFaultAdapter;
import com.sita.cfmoto.ui.view.CircularStatusView;
import com.sita.cfmoto.ui.widget.TreeView;
import com.sita.cfmoto.utils.LocalStorage;
import com.sita.cfmoto.utils.LogUtils;
import com.sita.cfmoto.utils.VehicleUtils;

import java.lang.reflect.Type;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ToastUtils;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class DeviceStatusActivity extends ActivityBase {
    String TAG = DeviceStatusActivity.class.getSimpleName();
    @Bind(R.id.device_state_btn_check)
    Button mBtnCheck;
    @Bind(R.id.device_state_btn_service)
    Button mBtnService;
    @Bind(R.id.device_state_view)
    CircularStatusView mDeviceStateView;
    @Bind(R.id.device_state_list_view)
    //TreeView mDeviceStateListView;
            RecyclerView mDeviceStateListView;
    @Bind(R.id.device_check_mark_value)
    TextView mTvMark;

    //    private DeviceFaultAdapter mTreeViewAdapter = null;
    private FaultAdapter mFaultListAdapter = null;
    private int mDeviceStatusMark = 0; //车况得分
    private Handler mHander = new Handler();

    public static Intent newIntent() {
        return new Intent(GlobalContext.getGlobalContext(), DeviceStatusActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_state_listview);
        ButterKnife.bind(this);
        mBtnCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2016/5/1 save the value
                LogUtils.d(TAG, "check button clicked");
                startCheckDevice();
            }
        });

        initToolbar(getResources().getString(R.string.vehicle_check));
        initDeviceStateView();
        initDeviceStateListView();
    }

    private void initDeviceStateView() {
        mDeviceStateView.setValue(100); //// TODO: 2016/5/2 get the data from where?
    }

    private void resetDeviceStateView() {
        mDeviceStateView.setValue(0);
        mTvMark.setText("--");
//        mDeviceStateListView.collapseGroup(0);
        mFaultListAdapter.setCount(0);
        mFaultListAdapter.notifyDataSetChanged();
    }

    private void setMark(int mark) {
        mTvMark.setText(String.valueOf(mark) + "分");
    }

    private void initDeviceStateListView() {
//        treeView.setHeaderView(getLayoutInflater().inflate(R.layout.list_head_view, treeView,
//                false));
//        if (mTreeViewAdapter == null) {
//            mTreeViewAdapter = new DeviceFaultAdapter(this, mDeviceStateListView);
//        }
//        mDeviceStateListView.setAdapter(mTreeViewAdapter);
        if (mFaultListAdapter == null) {
            mFaultListAdapter = new FaultAdapter();
        }
        mDeviceStateListView.setLayoutManager(new LinearLayoutManager(this));
        mDeviceStateListView.setAdapter(mFaultListAdapter);


//        mDeviceStateListView.expandGroups();
//        View view = getLayoutInflater().inflate(R.layout.device_state_listview_footer, mDeviceStateListView, false);
//        mTvTotalPrice = (TextView) view.findViewById(R.id.total_price);
//        mTvTotalPrice.setText("0");
//        mDeviceStateListView.addFooterView(view);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    private void startCheckDevice() {
        LogUtils.d(TAG, "startCheckDevice");

        if (!LocalStorage.hasBindVehicle()) {
            ToastUtils.show(getApplicationContext(), R.string.error_no_bind_vehicle);
            return;
        }

        resetDeviceStateView();

//        final ProgressDialog mProgressDialog = new ProgressDialog(this);
//        String str = "正在进行车辆自检，请稍后";
//        mProgressDialog.setMessage(str);
//        mProgressDialog.setCanceledOnTouchOutside(false);
//        mProgressDialog.show();
        long duration = 5000;
        mDeviceStateView.setValueAnimator(100, duration, new CircularStatusView.OnProgressFinieshed() {
            @Override
            public void onCompleted() {


            }
        });
//        mHander.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                FaultMapping.mapping(null);
//                mTreeViewAdapter.notifyDataSetChanged();
//
//                float total = DeviceFaultModel.getTotalPrice();
//                mTvTotalPrice.setText(String.valueOf((int) total));
//
//                mDeviceStatusMark = DeviceFaultModel.getStatusMark();
////                mDeviceStateView.setValue(mDeviceStatusMark);
////                mProgressDialog.dismiss();
//            }
//        }, 5000);

        BindedVehicle bindedVehicle = VehicleUtils.getCurrentSelectedVehicle();
        if (bindedVehicle == null) {
            return;
        }

        CfmotorCommonRequest2 request2 = new CfmotorCommonRequest2();
        request2.vin = bindedVehicle.vin;
        request2.vinCpy = bindedVehicle.vincpy;

        RestClient.getRestNormalService().fetchErrorList(request2, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                if (response.getStatus() == 200 && restResponse.mErrorCode.equals("0")) {

                    Type type = new TypeToken<Map<String, String>>(){}.getType();
                    String data = RestClient.getGson().toJson(restResponse.mData);
                    Map<String, String> errorMap = RestClient.getGson().fromJson(data, type);
                    LogUtils.d("error list", "error list size = " + errorMap.size());

                    DeviceFaultModel.clearData();
                    FaultMapping.mapping(errorMap);
                    DeviceFaultModel.getTotalPrice();
                    mDeviceStatusMark = DeviceFaultModel.getStatusMark();
                    setMark(mDeviceStatusMark);
                    mFaultListAdapter.setCount(DeviceFaultModel.getItems(0));
                    mFaultListAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
//        RikyInfoBtUtils.getFault(new RikyInfoBtUtils.OnFaultResultListener() {
//            @Override
//            public void onSuccess(Fault fault) {
//                // TODO: 2016/5/7 map fault
//                FaultMapping.mapping(fault);
//                mTreeViewAdapter.notifyDataSetChanged();
//
//                // TODO: 2016/5/9 get the total price
//                float total = DeviceFaultModel.getTotalPrice();
//                mTvTotalPrice.setText(String.valueOf((int)total));
//
//                mDeviceStatusMark = DeviceFaultModel.getStatusMark();
//                mDeviceStateView.setValue(mDeviceStatusMark);
//                mProgressDialog.dismiss();
//            }
//
//            @Override
//            public void onFail(Throwable throwable) {
//                mProgressDialog.dismiss();
//            }
//        });
    }

    @OnClick(R.id.device_state_btn_service)
    void goToServiceShop() {
        startActivity(new Intent(this, MapActivity.class));
    }

    class FaultAdapter extends RecyclerView.Adapter<FaultViewHolder> {

        private int count = 0;

        public void setCount(int count) {
            this.count = count;
        }

        @Override
        public int getItemCount() {
            return count;
        }

        @Override
        public FaultViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.device_state_list_item_view, parent, false);
            return new FaultViewHolder(view);
        }

        @Override
        public void onBindViewHolder(FaultViewHolder holder, int position) {
            DeviceFaultModel item = DeviceFaultModel.getFault(0, position);
            holder.item.setText(item.item);
            if (item.getStatus()) {
                holder.ok.setVisibility(View.VISIBLE);
                holder.fail.setVisibility(View.INVISIBLE);
            } else {
                holder.ok.setVisibility(View.INVISIBLE);
                holder.fail.setVisibility(View.VISIBLE);
            }
        }
    }

    class FaultViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.device_state_list_item)
        public TextView item;
        @Bind(R.id.device_state_icon_ok)
        public ImageView ok;
        @Bind(R.id.device_state_icon_fail)
        public ImageView fail;

        public FaultViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

        }
    }
}
